#include <57header.h>

// 服务端
int main(int argc,char*argv[])
{
    char *port = "8081";
    char *ip = "192.168.106.129";

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    // 如果8080被处于time_wait状态， 我们希望重新使用这个端口

    int num = 1;
    setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &num, sizeof(num));
     
    

    // 给服务端绑定端口
    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);

    int ret_bind = bind(socket_fd,(struct sockaddr *)&sockaddr, sizeof(sockaddr) );
    ERROR_CHECK(ret_bind, -1, "bind");

    // 让socket端点对象，开始启动监听
    int ret_listen = listen(socket_fd, 10);
    ERROR_CHECK(ret_listen, -1, "listen");


    struct sockaddr_in sockaddr_client;
    socklen_t len ;
    int socket_fd_new = accept(socket_fd,
                               (struct sockaddr *)&sockaddr_client,
                               &len) ;

    fd_set set;
    FD_ZERO(&set);

    while(1){
        FD_SET(STDIN_FILENO, &set);
        FD_SET(socket_fd_new, &set);

        select(10, &set, NULL, NULL, NULL);

        if(FD_ISSET(STDIN_FILENO, &set)){
            char buf[60] = {0};
            // 对客户端回复
            read(STDIN_FILENO, buf, sizeof(buf));
            send(socket_fd_new, buf, sizeof(buf), 0);
        }
        if(FD_ISSET(socket_fd_new, &set)){
            // 从网络中读数据
            char buf[60] = {0};
            int ret = recv(socket_fd_new,buf, sizeof(buf), 0);
            if(ret == 0){
                printf("对方断开链接 \n");
                break;
            }
            
            printf("client: %s \n", buf);
        }
    }

    close(socket_fd_new);
    close(socket_fd);
    return 0;
}

